import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import {
  DataTableComponent,
  TableWidthConfig,
  DialogService,
  IDrawerOpenResult,
  DrawerService,
} from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { SaleOrder } from 'src/app/@core/data/sale';
import { SalesOrderToWorkOrderComponent } from './sales-order-to-work-order/sales-order-to-work-order.component';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { DisApprovalReasonComponent } from '../../purchase/dis-approval-reason/dis-approval-reason.component';
import { ReviewDocComponent } from '../../basic-data/user-center/review-doc/review-doc.component';

@Component({
  selector: 'app-sales-order',
  templateUrl: './sales-order.component.html',
  styleUrls: ['./sales-order.component.scss'],
})
export class SalesOrderComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  SaleOrder: SaleOrder = {
    saleOrderId: 0, // 销售订单的唯一标识符
    quotationNum: '', // 报价单号
    saleOrderNum: '', // 销售订单号
    orderDate: null, // 订单日期
    customerOrderNum: '', // 客户订单号
    customerName: '', // 客户名称
    deliveryDate: null, // 交货日期
    status: '未开始审核', // 是否已审核
    isClosed: false, // 是否已关闭
    partTotalQuantity: 0, // 零件总数量
    partShippedQuantity: 0, // 已发货的零件数量
    partUnshippedQuantity: 0, // 未发货的零件数量
    advancePaymentAmount: 0, // 预付款金额
    creationDate: null, // 创建日期
    creator: '', // 创建者
    orderType: '', // 订单类型
    company: '', // 公司名称
    customerShortName: '', // 客户简称
    customerContact: '', // 客户联系人
    contactInfo: '', // 联系信息
    salesman: '', // 销售员
    department: '', // 部门
    settlementCurrency: '', // 结算货币
    settlementMethod: '', // 结算方式
    paymentTerm: '', // 付款条件
    deliveryAddress: '', // 交货地址
    remark: '', // 备注
    totalQuantity: 0, // 总数量
    totalAmountWithTax: 0, // 含税总金额
    totalTaxAmount: 0, // 总税额
    totalDiscountAmountWithTax: 0, // 含税折扣总金额
    totalDiscountTaxAmount: 0, // 折扣税额
    files: [], // 相关文件
    fileRemarks: [], // 文件备注
    saleOrderParts: [], // 销售订单零件列表
    customerContactID: undefined,
    customerID: undefined,
  };
  tableData = [];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '操作',
        fieldType: 'text',
        fixedLeft: '80px',
      },
      {
        field: 'name',
        header: '销售订单号',
        fieldType: 'text',
        fixedLeft: '410px',
      },
      {
        field: '客户单号',
        header: '客户单号',
        fieldType: 'text',
      },
      {
        field: '单据日期',
        header: '单据日期',
        fieldType: 'text',
      },
      {
        field: '客户全称',
        header: '客户全称',
        fieldType: 'text',
      },
      {
        field: '客户简称',
        header: '客户简称',
        fieldType: 'text',
      },
      {
        field: '业务员',
        header: '业务员',
        fieldType: 'text',
      },
      {
        field: '部门',
        header: '部门',
        fieldType: 'text',
      },
      {
        field: '是否结案',
        header: '是否结案',
        fieldType: 'text',
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: '总数',
        header: '总数',
        fieldType: 'text',
      },
      {
        field: '含税金额合计',
        header: '含税金额合计',
        fieldType: 'text',
      },
      {
        field: '税额合计',
        header: '税额合计',
        fieldType: 'text',
      },
      {
        field: '不含税金额合计',
        header: '不含税金额合计',
        fieldType: 'text',
      },
      {
        field: '折扣含税金额合计',
        header: '折扣含税金额合计',
        fieldType: 'text',
      },
      {
        field: '折扣税额合计',
        header: '折扣税额合计',
        fieldType: 'text',
      },
      {
        field: '折扣不含税金额合计',
        header: '折扣不含税金额合计',
        fieldType: 'text',
      },
      {
        field: '二维码',
        header: '二维码',
        fieldType: 'text',
      },
      {
        field: '制单人',
        header: '制单人',
        fieldType: 'text',
      },
      {
        field: '制单日期',
        header: '制单日期',
        fieldType: 'text',
      },
      {
        field: '日志',
        header: '日志',
        fieldType: 'text',
      },
      {
        field: '状态',
        header: '状态',
        fieldType: 'text',
        fixedRight: '0px',
      },
    ],
  } //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: '操作',
      width: '330px',
    },
    {
      field: '销售订单号',
      width: '150px',
    },
    {
      field: '客户单号',
      width: '150px',
    },
    {
      field: '单据日期',
      width: '150px',
    },
    {
      field: '公司抬头',
      width: '150px',
    },
    {
      field: '客户简称',
      width: '150px',
    },
    {
      field: '业务员',
      width: '150px',
    },
    {
      field: '部门',
      width: '150px',
    },
    {
      field: '状态',
      width: '150px',
    },
    {
      field: '是否结案',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '总数',
      width: '150px',
    },
    {
      field: '含税金额合计',
      width: '150px',
    },
    {
      field: '税额合计',
      width: '150px',
    },
    {
      field: '不含税金额合计',
      width: '150px',
    },
    {
      field: '折扣含税金额合计',
      width: '150px',
    },
    {
      field: '折扣税额合计',
      width: '150px',
    },
    {
      field: '折扣不含税金额合计',
      width: '150px',
    },
    {
      field: '二维码',
      width: '150px',
    },
    {
      field: '制单人',
      width: '150px',
    },
    {
      field: '制单日期',
      width: '150px',
    },
    {
      field: '审批',
      width: '150px',
    },
  ] //表格宽度配置
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '200px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '规格型号',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '计划发货日期',
      width: '200px',
    },
    {
      field: '实时库存',
      width: '150px',
    },
    {
      field: '数量',
      width: '170px',
    },
    {
      field: '单位',
      width: '150px',
    },
    {
      field: '单价(含税)',
      width: '170px',
    },
    {
      field: '单价（不含税）',
      width: '150px',
    },
    {
      field: '税率（%）',
      width: '170px',
    },
    {
      field: '折扣（%）',
      width: '150px',
    },
    {
      field: '折扣单价（含税）',
      width: '150px',
    },
    {
      field: '含税金额',
      width: '150px',
    },
    {
      field: '不含税金额',
      width: '150px',
    },
    {
      field: '税额',
      width: '150px',
    },
    {
      field: '折扣不含税金额',
      width: '150px',
    },
    {
      field: '折扣含税金额',
      width: '150px',
    },
    {
      field: '折扣税额',
      width: '150px',
    },
    {
      field: '二维码',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '来源报价单号',
      width: '150px',
    },
  ]
  msgs: { severity: any; summary: any; content: any }[];
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  checkedIds: any = [];
  fifter = {
    PartNum: '',
    PartName: '',
    CustomerName: '',
    CustomerOrderNum: '',
    CustomerShortName: '',
    StartTime: '',
    EndTime: '',
    QuotationNum: '',
    SaleOrderNum: '',
    PageNumber: 1, // 通常分页参数的初始值
    PageSize: 20, // 假设默认页面大小为10
  };
  date = [];
  Customer: any;
  splitBarSize = '0px';
  partDetailHeight = '100%';
  showDetailId: any;
  selectedRowIndex: any;
  partDetail: any = [];
  checkedCodes: any=[]
  // 打印：不新建组件，直接在 TS 里拼出打印 HTML
  constructor(
    private SharedMethodService: SharedMethodService,
    private Router: Router,
    private SalesService: SalesService,
    private DialogService: DialogService,
    private JobOrderService: JobOrderService,
    private dataSharingService: DataSharingService,
    private CustomerService: CustomerService,
    private drawerService: DrawerService,
  private ReviewRolesService: ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.SalesService.GetSaleOrders(this.fifter).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
    })
    this.CustomerService.GetPagedCustomer({
      PageNumber: 1,
      PageSize: 999,
    }).subscribe((data: any) => {
      this.Customer = data.items;
    })
  }
  filter() {
    this.SalesService.GetSaleOrders(this.fifter).subscribe((data: any) => {
      this.tableData = data.items;
      this.pager.total = data.totalCount;
      console.log(this.showDetailId);
      if (this.showDetailId) {
        this.showDetail(
          this.tableData.find(
            (item: any) => item.saleOrderId === this.showDetailId
          ),
          this.selectedRowIndex
        );
      }
    });
  }
  filter2() {
    this.fifter.PageNumber = 1;
    this.filter();
  }
  statusOption = {};
  reset() {
    this.fifter = {
      PartNum: '',
      PartName: '',
      CustomerName: '',
      CustomerOrderNum: '',
      CustomerShortName: '',
      StartTime: '',
      EndTime: '',
      QuotationNum: '',
      SaleOrderNum: '',
      PageNumber: 1, // 通常分页参数的初始值
      PageSize: 20, // 假设默认页面大小为10
    };
    this.date = [];
    this.filter();
  }
  creat() {
    this.Router.navigate(['/pages/sales-master/sales-order/add']);
  }
  edit(id: any) {
    this.Router.navigate(['/pages/sales-master/sales-order/edit', id]);
  }
  delete(id?: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: '',
      title: '删除',
      content: '删除后将无法恢复该数据！',
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (id) {
              this.SalesService.DeleteSaleOrders([id]).subscribe(
                (data: any) => {
                  this.showToast('success', '成功', '删除成功');
                  this.SalesService.GetSaleOrders(this.fifter).subscribe(
                    (data: any) => {
                      this.tableData = data.items;
                      this.pager.total = data.totalCount;
                    }
                  );
                },
                (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
            } else {
              this.SalesService.DeleteSaleOrders(this.checkedIds).subscribe(
                (data: any) => {
                  this.showToast('success', '成功', '删除成功');
                  this.checkedIds = [];
                  this.SalesService.GetSaleOrders(this.fifter).subscribe(
                    (data: any) => {
                      this.tableData = data.items;
                      this.pager.total = data.totalCount;
                    }
                  );
                },
                (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ) {
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'saleOrderId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'saleOrderNum'
    ).subscribe((data: any) => {
      this.checkedCodes = data;
    });
  } //获取选中行
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  pageIndexChange($event: any) {
    this.filter();
  } //切换页码
  pageSizeChange($event: any) {
    this.filter();
  } //改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  salesOrderToWorkerOrder(dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '600px',
      width: '1200px',
      backdropCloseable: true,
      data: this.checkedIds.map((id: any) => {
        return {
          id: id,
          code: this.tableData.find((item: any) => item.saleOrderId === id)
            .saleOrderNum,
        };
      }),
      title: '生产工单',
      content: SalesOrderToWorkOrderComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            const userinfoString = localStorage.getItem('userinfo');

            const data = results.modalContentInstance.checkedIds.map(
              (item: any) => {
                return {
                  jobNum: null,
                  saleOrderNum: item.saleOrderNum,
                  jobOrderType: '销售式工单',
                  productNum: item.partNum,
                  productName: item.partName,
                  partType: item.partType,
                  uom: item.partUOM,
                  productionQuantity: item.productionQuantity,
                  jobOrderPlanStartDate: item.jobOrderPlanStartDate,
                  jobOrderPlanEndDate: item.jobOrderPlanEndDate,
                  createTime: new Date(),
                  creator: JSON.parse(userinfoString).username,
                  note: '',
                  saleOrderPartId: item.saleOrderPartId,
                };
              }
            );
            this.JobOrderService.CreateJobOrdersBySalesOrderMaterialLineIds(
              data
            ).subscribe(
              (data: any) => {
                const message = data
                  .map((item: any) => item.jobOrderNum)
                  .join(',');
                this.showToast(
                  'success',
                  '成功',
                  '工单号' + message + '创建成功'
                );
                results.modalInstance.hide();
                this.checkedIds = []
                this.cleared()
              },
              (error) => {
                this.showToast('error', '错误', error.error);
              }
            );
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  salesOrderToWorkerOrderBefore() {
    if (this.checkedIds.length === 0) {
      this.showToast('error', '错误', '请选择销售订单');
    } else {
      if (this.CheckedRows.every((item) => item.status === '审核通过')) {
        this.salesOrderToWorkerOrder()
      }else{
        this.showToast('error', '错误', '请选择已审核的销售订单');
      }
    }
  }
  dateChange() {
    this.fifter.StartTime = this.date[0]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
    this.fifter.EndTime = this.date[1]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
  }
  closed(id: any) {
    this.SalesService.FinishSaleOrder(id).subscribe(
      (data: any) => {
        this.showToast('success', '成功', '结案成功');
        this.filter();
      },
      (error: any) => {
        if (error.status === 404) {
          this.showToast('error', '错误', '网络连接错误');
        } else {
          this.showToast('error', '错误', error.error);
        }
      }
    );
  } //结案
  unClosed(id: any) {
    this.SalesService.UnFinishSalesQuotation(id).subscribe(
      (data: any) => {
        this.filter();
        this.showToast('success', '成功', '反结案成功');
      },
      (error: any) => {
        if (error.status === 404) {
          this.showToast('error', '错误', '网络连接错误');
        } else {
          this.showToast('error', '错误', error.error);
        }
      }
    )
  } //反结案
  CheckedRows = [];
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
        this.CheckedRows = data;
      }
    );
  } //获取选中行
  transformSaleOrder() {
    if (this.CheckedRows.every((item) => item.status === '审核通过')) {
      if (this.checkCustomerIDs(this.CheckedRows)) {
        if (
          (this.CheckedRows[0].saleOrderParts = this.CheckedRows.flatMap(
            (item) =>
              item.saleOrderParts.filter(
                (part: { quantity: number; soldQuantity: number }) =>
                  part.quantity - part.soldQuantity > 0
              )
          ))
        ){
          this.dataSharingService.setData(
            this.CheckedRows.map((row) => row.saleOrderId)
          );
          this.Router.navigate(['/pages/sales-master/sales-Invoice/add'], {
            queryParams: { loadData: true },
          });
        }else {
          this.showToast('error', '错误', '请选择未发货的销售订单');
        }
      } else {
        this.showToast('error', '错误', '请选择相同客户的销售订单');
      }
    } else {
      this.showToast('error', '错误', '请选择已审核的销售订单');
    }
  }
  checkCustomerIDs(customerRows: any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].customerID;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every(
      (row: { customerID: any }) => row.customerID === firstCustomerID
    );
  }
  downloadTemplate() {
    this.SalesService.DownloadSaleOrderFileModel().subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '销售订单模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    });
  }
  file: any;
  importSalesQuotation(event: any) {
    this.file = event.target.files[0];
    this.SalesService.ImportSaleOrderFromExcel(this.file).subscribe(
      (data: any) => {
        this.SalesService.GetSaleOrders(this.fifter).subscribe((data: any) => {
          this.tableData = data.items;
          this.pager.total = data.totalCount;
          this.showToast('success', '成功', '导入成功');
        });
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
        this.fileInput2.nativeElement.value = '';
      }
    );
  }
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    this.fileInput2.nativeElement.click();
  }
  download() {
    this.SalesService.DownloadSaleOrderFile().subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '销售订单单据.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    });
  }
  results: IDrawerOpenResult;
  allLog() {
    this.SalesService.GetAllSaleOrderLogs({
      PageNumber: 1,
      PageSize: 999,
    }).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '销售顶单',
          header: '销售顶单',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        },
      ];
      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
  GetLogsById(id: any) {
    this.SalesService.GetLogsBySaleOrderId({
      Id: id,
      PageNumber: 1,
      PageSize: 9999,
    }).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '销售顶单',
          header: '销售顶单',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        },
      ];

      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
  showDetail(data: any, rowIndex: any) {
    this.showDetailId = data.saleOrderId;
    (this.partDetail = data.saleOrderParts), (this.partDetailHeight = '75%');
    this.splitBarSize = '10px';
    this.selectedRowIndex = rowIndex;
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  CloseSaleOrderParts(rowitem: any, closed: boolean) {
    if (closed) {
      this.SalesService.CloseSaleOrderParts(
        [rowitem.saleOrderPartId],
        true
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '结案成功');
          this.filter();
        },
        (error: any) => {
          if (error.status === 404) {
            this.showToast('error', '错误', '网络连接错误');
          } else {
            this.showToast('error', '错误', error.error);
          }
        }
      );
    } else {
      this.SalesService.CloseSaleOrderParts(
        [rowitem.saleOrderPartId],
        false
      ).subscribe(
        (data: any) => {
          this.showToast('success', '成功', '反结案成功');
          this.filter();
        },
        (error: any) => {
          if (error.status === 404) {
            this.showToast('error', '错误', '网络连接错误');
          } else {
            this.showToast('error', '错误', error.error);
          }
        }
      );
    }
  }
  launchReview() {
    const invalidStatus = this.CheckedRows.some(row => row.status === '审核通过' || row.status === '审核中')
    if (invalidStatus) {
        this.showToast('error', '错误', '所选单据已发起审核');
        return
    }
    if (this.checkedCodes.length < 1) {
      this.showToast('error', '错误', '请选择要发起审核的单据');
      return;
    }
    this.ReviewRolesService.StartApprovalFlow('销售订单审核流配置',this.checkedCodes).subscribe(
      (res: any) => {
        this.showToast('success', '成功', res);
        this.filter();
        this.checkedIds = [];
        this.checkedCodes = [];
      },
      (error: any) => {
        this.showToast('error', '错误', error.error);
      }
    );
  }
  clickCode(code: string, type: string, status?: string, dialogtype?: string) {
    let data = {
      code: code,
      type: type,
      disPlay: false,
    };
    const results = this.DialogService.open({
      id: 'custom',
      width: '90vw',
      maxHeight: '90vh',
      backdropCloseable: true,
      content: ReviewDocComponent,
      dialogtype: dialogtype,
      data:data,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '通过',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
            this.ReviewRolesService.ApproveNode(
              results.modalContentInstance.approvalNodeId,
              code
            ).subscribe((res: any) => {
              results.modalInstance.hide();
              this.showToast('success', '成功', '审批成功');
              this.filter();
            },error=>{
              this.showToast('error', '错误', error.error || '网络连接错误');
            }
          );
          }
          else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          cssClass: 'danger',
          text: '驳回',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
              console.log()
            if(results.modalContentInstance.reason){
              this.ReviewRolesService.RejectNode(
                results.modalContentInstance.approvalNodeId,
                code,
                results.modalContentInstance.reason
              ).subscribe(
                (res) => {
                  this.showToast('success', '成功', '审批成功');
                  results.modalInstance.hide();
                  this.filter();
                },
                (error: any) => {
                  this.showToast(
                    'error',
                    '错误',
                    error.error || '网络连接错误'
                  );
                }
              );
            }else{
              data.disPlay = true
              this.showToast('warn', '警告', '请填写驳回原因');
            }
          }else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl +'/' + url);
    return urls;
  }

  // 打印当前订单（优先当前详情所示，其次为仅勾选的一条）
  printCurrentOrder(): void {
    // 1) 获取目标订单
    let target: any = null;
    if (this.showDetailId) {
      target = (this.tableData as any[]).find(
        (o: any) => o.saleOrderId === this.showDetailId
      );
    }
    if (!target && this.CheckedRows && this.CheckedRows.length === 1) {
      target = this.CheckedRows[0];
    }
    if (!target) {
      this.showToast('warn', '提示', '请选择一个订单（点击行展开详情或仅勾选一条）');
      return;
    }

    // 2) 直接构建打印 HTML（内联样式），使用隐藏 iframe 打印
    const html = this.buildPrintHtml(target);

    const iframe = document.createElement('iframe');
    iframe.style.position = 'fixed';
    iframe.style.right = '0';
    iframe.style.bottom = '0';
    iframe.style.width = '0';
    iframe.style.height = '0';
    iframe.style.border = '0';
    iframe.style.visibility = 'hidden';
    document.body.appendChild(iframe);

    const doc = iframe.contentDocument || iframe.contentWindow?.document;
    if (!doc) {
      document.body.removeChild(iframe);
      this.showToast('error', '错误', '无法初始化打印窗口');
      return;
    }
    doc.open();
    doc.write(html);
    doc.close();

    setTimeout(() => {
      try {
        iframe.contentWindow?.focus();
        iframe.contentWindow?.print();
      } finally {
        setTimeout(() => {
          if (iframe && iframe.parentNode) {
            iframe.parentNode.removeChild(iframe);
          }
        }, 400);
      }
    }, 200);
  }

  // 批量打印选中的订单（支持1..N条，自动分页）
  printSelectedOrders(): void {
    // 直接从表格获取选中行的完整数据，确保包含 saleOrderParts
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (rows: any[]) => {
        const selected = Array.isArray(rows) ? rows : [];
        if (!selected.length) {
          this.showToast('warn', '提示', '请至少勾选一条订单进行打印');
          return;
        }
        const html = this.buildBatchPrintHtml(selected);
        const iframe = document.createElement('iframe');
        iframe.style.position = 'fixed';
        iframe.style.right = '0';
        iframe.style.bottom = '0';
        iframe.style.width = '0';
        iframe.style.height = '0';
        iframe.style.border = '0';
        iframe.style.visibility = 'hidden';
        document.body.appendChild(iframe);
        const doc = iframe.contentDocument || iframe.contentWindow?.document;
        if (!doc) {
          document.body.removeChild(iframe);
          this.showToast('error', '错误', '无法初始化打印窗口');
          return;
        }
        doc.open();
        doc.write(html);
        doc.close();

        setTimeout(() => {
          try {
            iframe.contentWindow?.focus();
            iframe.contentWindow?.print();
          } finally {
            setTimeout(() => {
              if (iframe && iframe.parentNode) {
                iframe.parentNode.removeChild(iframe);
              }
            }, 400);
          }
        }, 200);
      }
    );
  }

  // 构建批量打印 HTML（多个订单，每个订单单独一页）
  private buildBatchPrintHtml(orders: any[]): string {
    const style = `
      <style>
      @page { size: A4; margin: 10mm; }
      body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
      .sheet { width: 210mm; min-height: 297mm; padding: 12mm; margin: 0 auto; page-break-after: always; }
      .sheet:last-child { page-break-after: auto; }
      .header { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; }
      .header .company { font-size: 12px; }
      .header .title { text-align: center; font-size: 24px; font-weight: 700; letter-spacing: 2px; }
      .hr { border-top: 2px solid #333; margin: 6px 0 10px; }
      .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px 24px; font-size: 12px; }
      .address {  font-size: 12px; margin-top: 8px; }
      table { width: 100%; border-collapse: collapse; margin-top: 10px; }
      th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
      th { background: #fafafa; }
      .num { text-align: right; }
      td.qr, th.qr { text-align: center; }
      td.qr img { width: 56px; height: 56px; object-fit: contain; }
      .sign { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px 24px; font-size: 12px; margin-top: 12px; }
      .footer { display: flex; justify-content: space-between; font-size: 12px; margin-top: 12px; border-top: 1px solid #333; padding-top: 6px; }
      </style>`;

    const toNum = (x: any) => { const n = Number(x); return isNaN(n) ? 0 : n; };
    const to2 = (n: any) => typeof n === 'number'
      ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : (n ?? '');
    const fmtDate = (d: any) => {
      if (!d) return '';
      const dt = new Date(d); if (isNaN(dt.getTime())) return d;
      const y = dt.getFullYear(); const m = String(dt.getMonth()+1).padStart(2,'0'); const da = String(dt.getDate()).padStart(2,'0');
      return `${y}-${m}-${da}`;
    };
    const firstOr = (u: string) => (u && u.split(',')[0]) || '';
    const absUrl = (u: string) => {
      if (!u) return '';
      if (/^https?:\/\//i.test(u)) return u;
      const base = (environment.modifiedApiUrl || '').replace(/\/+$/, '');
      const path = ('' + u).replace(/^\/+/, '');
      return base ? `${base}/${path}` : u;
    };

    const total = orders.length;
    const pages = orders.map((order: any, idx: number) => {
      const parts = order?.saleOrderParts || [];
      const sumQty = parts.reduce((s: number, p: any) => s + toNum(p?.quantity), 0);
      const sumAmtWithTax = parts.reduce((s: number, p: any) => s + (p?.amountWithTax != null ? toNum(p?.amountWithTax) : toNum(p?.priceWithTax) * toNum(p?.quantity)), 0);
      const sumTax = parts.reduce((s: number, p: any) => s + (p?.taxAmount != null ? toNum(p?.taxAmount) : 0), 0);

      const rows = parts.map((p: any, i: number) => `
        <tr>
          <td>${i + 1}</td>
          <td>${p?.partNum ?? ''}</td>
          <td>${p?.partName ?? ''}</td>
          <td>${p?.partType ?? ''}</td>
          <td>${p?.partUOM ?? ''}</td>
          <td class="num">${to2(toNum(p?.priceWithTax))}</td>
          <td class="num">${to2(toNum(p?.quantity))}</td>
          <td class="num">${to2(p?.amountWithTax != null ? toNum(p?.amountWithTax) : toNum(p?.priceWithTax) * toNum(p?.quantity))}</td>
          <td>${p?.remark ?? ''}</td>
          <td class="qr">${firstOr(p?.qrCode || '') ? `<img src="${absUrl(firstOr(p?.qrCode || ''))}" alt="qr" />` : ''}</td>
        </tr>`).join('');

      return `
      <div class="sheet">
        <div class="header">
          <div class="company">${order?.company ?? '公司抬头'}</div>
          <div class="title">销售订单</div>
          <div></div>
        </div>
        <div class="hr"></div>
        <div class="info">
          <div><strong>单号：</strong>${order?.saleOrderNum ?? ''}</div>
          <div><strong>客户名称：</strong>${order?.customerName ?? ''}</div>
          <div><strong>客户订单号：</strong>${order?.customerOrderNum ?? ''}</div>
          <div><strong>单据日期：</strong>${fmtDate(order?.orderDate)}</div>
          <div><strong>业务员：</strong>${order?.salesman ?? ''}</div>
          <div><strong>部门：</strong>${order?.department ?? ''}</div>
        </div>
        <div class="address"><strong>送货地址：</strong>${order?.deliveryAddress ?? ''}</div>
        <table>
          <thead>
            <tr>
              <th style="width:44px;">序</th>
              <th style="width:140px;">物料编码</th>
              <th style="width:140px;">物料名称</th>
              <th style="width:140px;">规格/型号</th>
              <th style="width:60px;">单位</th>
              <th style="width:100px;" class="num">含税单价(元)</th>
              <th style="width:80px;" class="num">数量</th>
              <th style="width:120px;" class="num">合价(元)</th>
              <th style="width:120px;">备注</th>
              <th style="width:64px;" class="qr">二维码</th>
            </tr>
          </thead>
          <tbody>
            ${rows || '<tr><td colspan="10" style="text-align:center;">无明细</td></tr>'}
            <tr>
              <td colspan="6"><strong>合计数量</strong></td>
              <td class="num">${to2(sumQty)}</td>
              <td class="num">${to2(sumAmtWithTax)}</td>
              <td colspan="2"></td>
            </tr>
            <tr>
              <td colspan="6"><strong>含税金额合计</strong></td>
              <td></td>
              <td class="num">${to2(sumAmtWithTax)}</td>
              <td colspan="2"></td>
            </tr>
            <tr>
              <td colspan="6"><strong>税额合计</strong></td>
              <td></td>
              <td class="num">${to2(sumTax)}</td>
              <td colspan="2"></td>
            </tr>
          </tbody>
        </table>
        <div class="sign">
          <div>
            <div><strong>制单：</strong>${order?.creator ?? ''}</div>
            <div><strong>制单日期：</strong>${fmtDate(order?.creationDate)}</div>
          </div>
          <div>
            <div><strong>客户签收：</strong></div>
            <div>&nbsp;</div>
          </div>
        </div>
        <div class="footer">
          <div>本单据由系统自动生成</div>
          <div>第 ${idx + 1} / ${total} 页</div>
        </div>
      </div>`;
    }).join('');

    return `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>${pages}</body></html>`;
  }

  private buildPrintHtml(order: any): string {
    const parts = order?.saleOrderParts || [];
    const toNum = (x: any) => { const n = Number(x); return isNaN(n) ? 0 : n; };
    const to2 = (n: any) => typeof n === 'number'
      ? n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      : (n ?? '');
    const fmtDate = (d: any) => {
      if (!d) return '';
      const dt = new Date(d); if (isNaN(dt.getTime())) return d;
      const y = dt.getFullYear(); const m = String(dt.getMonth()+1).padStart(2,'0'); const da = String(dt.getDate()).padStart(2,'0');
      return `${y}-${m}-${da}`;
    };
    const firstOr = (u: string) => (u && u.split(',')[0]) || '';
    const absUrl = (u: string) => {
      if (!u) return '';
      if (/^https?:\/\//i.test(u)) return u;
      const base = (environment.modifiedApiUrl || '').replace(/\/+$/, '');
      const path = ('' + u).replace(/^\/+/, '');
      return base ? `${base}/${path}` : u;
    };
    const sumQty = parts.reduce((s: number, p: any) => s + toNum(p?.quantity), 0);
    const sumAmtWithTax = parts.reduce((s: number, p: any) => s + (p?.amountWithTax != null ? toNum(p?.amountWithTax) : toNum(p?.priceWithTax) * toNum(p?.quantity)), 0);
    const sumTax = parts.reduce((s: number, p: any) => s + (p?.taxAmount != null ? toNum(p?.taxAmount) : 0), 0);

  const rows = parts.map((p: any, i: number) => `
      <tr>
        <td>${i + 1}</td>
        <td>${p?.partNum ?? ''}</td>
        <td>${p?.partName ?? ''}</td>
        <td>${p?.partType ?? ''}</td>
        <td>${p?.partUOM ?? ''}</td>
        <td class="num">${to2(toNum(p?.priceWithTax))}</td>
        <td class="num">${to2(toNum(p?.quantity))}</td>
        <td class="num">${to2(p?.amountWithTax != null ? toNum(p?.amountWithTax) : toNum(p?.priceWithTax) * toNum(p?.quantity))}</td>
    <td>${p?.remark ?? ''}</td>
    <td class="qr">${firstOr(p?.qrCode || '') ? `<img src="${absUrl(firstOr(p?.qrCode || ''))}" alt="qr" />` : ''}</td>
      </tr>`).join('');

    const style = `
      <style>
      @page { size: A4; margin: 10mm; }
      body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', 'PingFang SC', 'Microsoft YaHei', sans-serif; }
      .sheet { width: 210mm; min-height: 297mm; padding: 12mm; margin: 0 auto; }
      .header { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; }
      .header .company { font-size: 12px; }
  .header .title { text-align: center; font-size: 24px; font-weight: 700; letter-spacing: 2px; }
      .hr { border-top: 2px solid #333; margin: 6px 0 10px; }
      .info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px 24px; font-size: 12px; }
      .address {  font-size: 12px; margin-top: 8px; }
      table { width: 100%; border-collapse: collapse; margin-top: 10px; }
      th, td { border: 1px solid #333; padding: 6px 8px; font-size: 12px; }
      th { background: #fafafa; }
      .num { text-align: right; }
  td.qr, th.qr { text-align: center; }
  td.qr img { width: 56px; height: 56px; object-fit: contain; }
      .sign { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px 24px; font-size: 12px; margin-top: 12px; }
      .footer { display: flex; justify-content: space-between; font-size: 12px; margin-top: 12px; border-top: 1px solid #333; padding-top: 6px; }
      </style>`;

    const html = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/>${style}</head><body>
      <div class="sheet">
        <div class="header">
          <div class="company">${order?.company ?? '公司抬头'}</div>
          <div class="title">销售订单</div>
          <div></div>
        </div>
        <div class="hr"></div>
        <div class="info">
          <div><strong>单号：</strong>${order?.saleOrderNum ?? ''}</div>
          <div><strong>客户名称：</strong>${order?.customerName ?? ''}</div>
          <div><strong>客户订单号：</strong>${order?.customerOrderNum ?? ''}</div>
          <div><strong>单据日期：</strong>${fmtDate(order?.orderDate)}</div>
          <div><strong>业务员：</strong>${order?.salesman ?? ''}</div>
          <div><strong>部门：</strong>${order?.department ?? ''}</div>
        </div>
        <div class="address"><strong>送货地址：</strong>${order?.deliveryAddress ?? ''}</div>
        <table>
          <thead>
            <tr>
              <th style="width:44px;">序</th>
              <th style="width:140px;">物料编码</th>
              <th style="width:140px;">物料名称</th>
              <th style="width:140px;">规格/型号</th>
              <th style="width:60px;">单位</th>
              <th style="width:100px;" class="num">含税单价(元)</th>
              <th style="width:80px;" class="num">数量</th>
              <th style="width:120px;" class="num">合价(元)</th>
              <th style="width:120px;">备注</th>
              <th style="width:64px;" class="qr">二维码</th>
            </tr>
          </thead>
          <tbody>
            ${rows || '<tr><td colspan="10" style="text-align:center;">无明细</td></tr>'}
            <tr>
              <td colspan="6"><strong>合计数量</strong></td>
              <td class="num">${to2(sumQty)}</td>
              <td class="num">${to2(sumAmtWithTax)}</td>
              <td colspan="2"></td>
            </tr>
            <tr>
              <td colspan="6"><strong>含税金额合计</strong></td>
              <td></td>
              <td class="num">${to2(sumAmtWithTax)}</td>
              <td colspan="2"></td>
            </tr>
            <tr>
              <td colspan="6"><strong>税额合计</strong></td>
              <td></td>
              <td class="num">${to2(sumTax)}</td>
              <td colspan="2"></td>
            </tr>
          </tbody>
        </table>
        <div class="sign">
          <div>
            <div><strong>制单：</strong>${order?.creator ?? ''}</div>
            <div><strong>制单日期：</strong>${fmtDate(order?.creationDate)}</div>
          </div>
          <div>
            <div><strong>客户签收：</strong></div>
            <div>&nbsp;</div>
          </div>
        </div>
        <div class="footer">
          <div>本单据由系统自动生成</div>
          <div>第 1 / 1 页</div>
        </div>
      </div>
    </body></html>`;
    return html;
  }

}
